//
//  MallTypeView.swift
//  Box
//
//  Created by mn on 2025/4/2.
//

import UIKit
import Kingfisher
class MallTypeView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    var selectType:((String) -> Void)?
    
    var categories = [MallType](){
        didSet{
            collectionView.reloadData()
        }
    }
    private let collectionView: UICollectionView

    init() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        super.init(frame: .zero)
        setupCollectionView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupCollectionView() {
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.registerCell(MallTypeCell.self)

        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    // MARK: - UICollectionView DataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: MallTypeCell = collectionView.cell(indexPath)
        let category = categories[indexPath.item]
        cell.titleLabel.text = category.name
        cell.imageView.kf.setImage(with: URL(string: category.imgUrl))
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectType?(categories[indexPath.item].id)
    }

    // MARK: - UICollectionViewDelegateFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 80, height: 60) // 每个分类项大小
    }
}
